<?php
/*
 * 手机客户端 有奖问答 获取问题接口
 * 2013-12-04
 */
 
include "inc/public_header.php";

include "func/user.php";				//用户信息处理函数

$code = $_REQUEST["code"];			//活动代码

//获取用户信息
$uInfoArr = user_getInfoFromUUID();
if(!$uInfoArr){
	echo json_encode(array("success"=>"0","errCode"=>"0","msg"=>"没有获取到用户信息"));
	die;
}
$uid = $uInfoArr["uid"];

if(!$code){
	echo json_encode(array("success"=>"0","errCode"=>"-1","msg"=>"没有获取到活动代码"));
	die;
}

$reJson = array(); //构建返回值

//判断用户是否参与过答题
$sql = "select id from ac_question_user where acode='".$code."' and uid='".$uid."' and aresult=1";
$db->query($sql);
if($db->next_record()){
	echo json_encode(array("success"=>"1","isParticipate"=>"1","msg"=>"已经答过题"));
	die;
}


//随机抽取问答题
$sql = "select id,atype,acode,aindex,acontent from ac_question_info where atype=2 order by aindex asc";
$db->query($sql);
$queArr = array();
while($db->next_record()){
	$queArr[] = array(
		"id" 			=> $db->f("id")			//题目主键
		,"aindex" 		=> $db->f("aindex")		//题目索引
		,"acontent" 	=> $db->f("acontent")	//题目内容
	);
}
shuffle($queArr); //随机打乱数组

$reJson["success"] = "1";
$reJson["isParticipate"] = "0"; //标记没答过题

//设置问答题
$reJson["completion"] = array($queArr[0]["acontent"]);
$wdQue = $queArr[0]["id"]; //问答题主键


$ques = ""; //答题主键

//获取全部选择题
$sql = "select id,atype,acode,aindex,acontent,aresult from ac_question_info where atype=0 order by aindex asc";
$db->query($sql);
$queArr = array();			//题目信息素组
$optionsArr = array();		//题目选项数组

while($db->next_record()){
	$queArr[] = array(
		"id" 			=> $db->f("id")			//题目主键
		,"aindex" 		=> $db->f("aindex")		//题目索引
		,"acontent" 	=> $db->f("acontent")	//题目内容
	);
	//列出当前题目的选项信息
	$sql = "select id,pid,aindex,aoption from ac_question_options where pid=".$db->f("id")." order by aindex asc";
	$db1->query($sql);
	$oArr = array(); //对应题目的选项素组
	while($db1->next_record()){
		$oArr[] = 
			array(
				"id"		=> $db1->f("id")		//选项主键
				,"pid"		=> $db1->f("pid")		//题目主键
				,"aindex"	=> $db1->f("aindex")	//选项索引
				,"aoption"	=> substr($db1->f("aoption"),4,strlen($db1->f("aoption")))	//选项内容
			);
	}
	$optionsArr[$db->f("id")] = $oArr;
}
shuffle($queArr); //随机打乱数组

//选择题数组
$choiceQuestion = array();
$reJson["choiceQuestion"] = &$choiceQuestion;

for($i=0;$i<9;$i++){
	$optJson = array();
	$opts = $optionsArr[$queArr[$i]["id"]]; //选项数组
	for($j=0;$j<count($opts);$j++){
		$optJson[] = $opts[$j]["aoption"];
	}
	$choiceQuestion[] = array(
		"title"=>$queArr[$i]["acontent"]
		,"option"=>$optJson
	);
}

//将题目主键先提交到数据库
$sql = "select id from ac_question_user where acode='".$code."' and uid='".$uid."'";
//判断以前有没有取过题目
$db->query($sql);
if($db->next_record()){
	$sql = "update ac_question_user set qid='".$ques."',ctime=now() where acode='".$code."' and uid='".$uid."'";
}else{
	$sql = "insert into ac_question_user (uid,ctime,acode,aresult,aflag,qid,away) values(".$uid.",now(),'".$code."','0','0','".$ques."',1)";
}
$db->query($sql);

echo json_encode($reJson);
die;
?>